import router from "~/router";
import { useCookies } from '@vueuse/integrations/useCookies';
import { ElNotification } from 'element-plus';
import store from './store';

//全局前置守卫
router.beforeEach(async(to, from, next) => {
    const token = useCookies().get('user-token');
    //没有登陆，强制跳转回登录页
    if (!token && to.path != '/login') {
        ElNotification({
            message: '请先登录',
            type: 'error',
            duration: 3000
        })
        return next({ path: '/login' });
    }
    //防止重复登录
    if (token && to.path == '/login') {
        ElNotification({
            message: '请勿重复登录',
            type: 'error',
            duration: 3000
        })
        return next({ path: from.path ? from.path : '/' });
    }
    //如果用户登录了，自动获取用户信息，并储存在vuex中
    if (token) {
        await store.dispatch('getinfo');
    }
    //设置页面标题
    let title = (to.meta.title?to.meta.title:'')+'-味蕾旅行家';
    document.title = title;
    next();
});